package com.tx.blog.article.service.impl;

import com.tx.blog.article.dao.IArticleDao;
import com.tx.blog.article.service.IArticleService;
import com.tx.blog.article.vo.ArticleTypeVo;
import com.tx.blog.article.vo.ArticleVo;
import com.tx.blog.user.dao.IUserDao;
import com.tx.blog.util.IdGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ：tx
 * @description： 文章实现类
 * @date ：Created in 2019/4/26 16:03
 * @modified By：
 * @version:
 */
@Service
public class ArticleServiceImpl implements IArticleService {

    @Autowired
    IArticleDao articleDao;

    @Autowired
    IUserDao userDao;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public List<ArticleVo> findAll(String userId) {
        return articleDao.findAll(userId);
    }

    @Override
    public boolean saveArticle(String userId, ArticleVo articleVo) {
        //保存文章类型
        String typeId = saveArticleType(articleVo);
        //获取文章id
        Long articleId = IdGenerator.get().nextId();
        //保存文章
        articleVo.setArticleId(articleId+"");
        articleVo.setTypeId(typeId);
        articleDao.saveArticle(articleVo);

        //保存文章用户关联表
        userDao.saveUserArticle(userId,articleId);
        logger.info("保存文章id为："+articleId+",userId为："+userId);
        return true;
    }

    @Override
    public void deleteArticle(String userId, ArticleVo articleVo) {
        //删除关联表
        userDao.deleteUserArticle(userId,articleVo.getArticleId());
        //删除文章表
        articleDao.deleteArticle(articleVo);
        logger.info("删除文章id为："+articleVo.getArticleId()+",userId为："+userId);
    }

    @Override
    public void updateArticle(String userId, ArticleVo articleVo) {
        //修改文章类型
        String typeId = saveArticleType(articleVo);
        articleVo.setTypeId(typeId);
        //修改文章
        articleDao.updateArticle(articleVo);
        logger.info("修改文章id为："+articleVo.getArticleId()+",userId为："+userId);
    }

    private String saveArticleType(ArticleVo articleVo) {
        String typeId = articleVo.getTypeId();
        if (typeId.isEmpty()) { //如果又新加了
            typeId = IdGenerator.get().nextId() + "";
            ArticleTypeVo articleTypeVo = new ArticleTypeVo(typeId, articleVo.getTypeName());
            articleDao.addNewType(articleTypeVo);
        }
        return typeId;
    }

    @Override
    public ArticleVo findArticle(String articleId) {
        return articleDao.findArticle(articleId);
    }

    @Override
    public void addNewType(ArticleTypeVo articleTypeVo) {
        Long typeCode = IdGenerator.get().nextId();
        articleTypeVo.setArticleTypeCode(typeCode+"");
        articleDao.addNewType(articleTypeVo);
    }

    @Override
    public List<ArticleTypeVo> findAllArticleType(String userId) {
        return articleDao.findAllArticleType(userId);
    }
}
